const Controller = require('egg').Controller
const path = require('path');
const fs = require('fs');
const awaitWriteStream = require('await-stream-ready').write;
const sendToWormhole = require('stream-wormhole');

class editUserInfo extends Controller {
    async index() {
        const { ctx } = this
        const getInfo = await ctx.service.editUserInfo.find();
        await ctx.render('editUserInfo.html', {
            user: getInfo,
            message: ''
        })
    }

    async editInfo() {
        const { ctx } = this

        const stream = await ctx.getFileStream();

        const filename = Math.random().toString(36).substr(2) + new Date().getTime() + path.extname(stream.filename).toLocaleLowerCase();

        const target = path.join(this.config.baseDir, 'app/public/uploads', filename);

        const writeStream = fs.createWriteStream(target);

        try {
            //异步把文件流 写入
            await awaitWriteStream(stream.pipe(writeStream));
        } catch (err) {
            //如果出现错误，关闭管道
            await sendToWormhole(stream);
            throw err;
        }

        let url='/public/uploads/' + filename
        let data=stream.fields
        data.url=url
        
        const getData=await ctx.service.editUserInfo.UpData(data)
        
        if(!getData){
            await ctx.render('editUserInfo.html', {
                message: '编辑个人信息失败'
            })
        }else{
            const getResult=await ctx.service.editUserInfo.Result(data,getData)
            if (getResult) {
                ctx.redirect('/')
            }
        }
    }
}

module.exports = editUserInfo